package com.leetcode.LC_MED;

public class LC738 {
    public int monotoneIncreasingDigits(int n) {

        char[] chars = String.valueOf(n).toCharArray();
        for (int i = chars.length - 1; i > 0; i--) {
            if (chars[i - 1] > chars[i]) {
                chars[i - 1] -= 1;
                for (int j = i; j < chars.length; j++) {
                    chars[j] = '9';
                }
            }
        }
        StringBuilder sb = new StringBuilder();
        for (char aChar : chars) {
            sb.append(aChar);
        }
        return Integer.parseInt(sb.toString());
    }

    public int monotoneIncreasingDigits_2(int n) {
        char[] chars = String.valueOf(n).toCharArray();
        int start = chars.length;
        for (int i = chars.length - 1; i > 0; i--) {
            if (chars[i - 1] > chars[i]) {
                chars[i - 1] -= 1;
                start = i;
            }
        }
        for (int j = start; j < chars.length; j++) {
            chars[j] = '9';
        }
        StringBuilder sb = new StringBuilder();
        for (char aChar : chars) {
            sb.append(aChar);
        }
        return Integer.parseInt(sb.toString());
    }
}
